package com.kai.steering.data.service.service.impl;

import com.kai.steering.common.vo.Result;
import com.kai.steering.common.web.ctl.BaseController;
import com.kai.steering.common.web.service.impl.BaseServiceImpl;
import com.kai.steering.common.web.vo.ReturnCodeExt;
import com.kai.steering.data.service.entity.domainObject.CaretakerDO;
import com.kai.steering.data.service.entity.domainObject.UserDO;
import com.kai.steering.data.service.entity.dto.Login;
import com.kai.steering.data.service.entity.dto.UserQueryDTO;
import com.kai.steering.data.service.entity.po.Caretaker;
import com.kai.steering.data.service.entity.vo.CaretakerVO;
import com.kai.steering.data.service.mapper.CaretakerMapper;
import com.kai.steering.data.service.service.CaretakerService;
import com.kai.steering.data.service.service.LoginRegisterService;
import com.kai.steering.data.service.service.UserService;
import com.kai.steering.data.service.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @ Author     ：LiuKai.
 * @ Date       ：Created in 10:28 2022-2-28
 * @ Description：登录服务实现类
 * @ Modified By：
 * @Version:
 */
@Slf4j
@Service
public class LoginRegisterServiceImpl   implements LoginRegisterService {
    @Autowired
    private CaretakerService caretakerService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil; // 假设你有一个生成JWT的工具类
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    /**
     * 登录
     */
    public String login(Login login) {

        /**
         * 构建对象
         */
        //HttpServletRequest对象
        HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //构建存储管理员或用户对象对象
        if (login.getPattern() == 0) {//判断用户属性
            //构建管理员
            CaretakerDO caretaker = caretakerService.getCaretakerById(login.getUserID());
            //判断账号存在且密码相等
            if ((caretaker != null|| StringUtils.isEmpty(caretaker.getCaretakerId())) && caretaker.getPassword().equals(login.getPassword())) {
                //在Session储存 重定向也可以
                //request.setAttribute("caretakerDO",caretakerDO); //只能在同一个request中有效
                //储存
                request.getSession().setAttribute("caretakerDO", caretaker);//在Session储存 重定向也可以
                return "true";
            }
            throw ReturnCodeExt.BUSINESS_EXCEPTION.getException("账号/密码不存在");
        } else{
            //构建用户
//            UserDO userDO = userService.getUserById(login.getUserID(),false);
            try {
//                String encryptedPassword = passwordEncoder.encode(login.getPassword());
                authenticate(login.getUserID(), login.getPassword());




//            userService.loadUserByUsername(login.getUserID());
            final String token = jwtTokenUtil.generateToken(login.getUserID());
            return token;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

    }

    @Override
    public boolean register(UserDO userDO) {
        UserDO result = userService.saveUser(userDO);
        if (result==null||result.getUserId()==null){
            throw  ReturnCodeExt.BUSINESS_EXCEPTION.getException("注册失败");
        }
        return true;
    }
    private void authenticate(String username, String password) throws Exception {
        try {
            Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));

            SecurityContextHolder.getContext().setAuthentication(authenticate);

            // 检查认证对象是否存在
            if (authenticate == null) {
                // 没有认证信息，可能是未登录或认证失败
                System.out.println("用户未认证或认证失败");
            } else {
                // 认证对象存在，检查是否认证成功
                if (authenticate.isAuthenticated()) {
                    // 用户已成功认证
                    System.out.println("用户已认证");

                    // 获取认证的用户信息
                    Object principal = authenticate.getPrincipal();
                    if (principal instanceof UserDetails) {
                        UserDetails userDetails = (UserDetails) principal;
                        System.out.println("用户名: " + userDetails.getUsername());
                        System.out.println("权限: " + userDetails.getAuthorities());
                    } else {
                        System.out.println("获取到的principal不是UserDetails对象");
                    }
                } else {
                    // 用户未认证或认证失败
                    System.out.println("用户未认证或认证失败");
                }


            }

        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS", e);
        }
    }

}
